import { useState } from 'react';
import { motion } from 'framer-motion';
import { Link } from 'react-router-dom';
import Navbar from '@/components/Navbar';
import Footer from '@/components/Footer';
import { useLanguage } from '@/contexts/LanguageContext';
import { useAuth } from '@/contexts/authContext';
import { cn } from '@/lib/utils';

// 用户资料类型定义
interface UserProfile {
  fullName: string;
  email: string;
  phone: string;
  address: string;
  city: string;
  zipCode: string;
  country: string;
}

// 订单类型定义
interface Order {
  id: number;
  date: string;
  total: number;
  status: 'pending' | 'processing' | 'shipped' | 'delivered' | 'cancelled';
  items: number;
}

export default function User() {
  const { t } = useLanguage();
  const { user, isAuthenticated, logout } = useAuth();
  const [activeTab, setActiveTab] = useState('profile');
  const [isEditing, setIsEditing] = useState(false);
  
  // 模拟用户资料数据
  const [profile, setProfile] = useState<UserProfile>({
    fullName: '张明',
    email: 'zhangming@example.com',
    phone: '13800138000',
    address: '北京市朝阳区建国路88号',
    city: '北京市',
    zipCode: '100022',
    country: '中国'
  });
  
  // 模拟订单历史数据
  const orders: Order[] = [
    { id: 1001, date: '2025-08-10', total: 329.97, status: 'delivered', items: 3 },
    { id: 987, date: '2025-07-25', total: 159.99, status: 'delivered', items: 2 },
    { id: 952, date: '2025-07-03', total: 89.50, status: 'shipped', items: 1 },
    { id: 921, date: '2025-06-18', total: 459.95, status: 'delivered', items: 4 }
  ];
  
  // 处理资料编辑提交
  const handleProfileSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setIsEditing(false);
    // 在实际应用中，这里会有API调用来保存用户资料
  };
  
  // 获取订单状态的中文显示和样式
  const getOrderStatusInfo = (status: Order['status']) => {
    switch (status) {
      case 'pending':
        return { text: '待付款', className: 'bg-yellow-100 text-yellow-800' };
      case 'processing':
        return { text: '处理中', className: 'bg-blue-100 text-blue-800' };
      case 'shipped':
        return { text: '已发货', className: 'bg-purple-100 text-purple-800' };
      case 'delivered':
        return { text: '已送达', className: 'bg-green-100 text-green-800' };
      case 'cancelled':
        return { text: '已取消', className: 'bg-red-100 text-red-800' };
      default:
        return { text: status, className: 'bg-gray-100 text-gray-800' };
    }
  };
  
  // 如果用户未登录，显示登录提示
  if (!isAuthenticated) {
    return (
      <div className="min-h-screen flex flex-col">
        <Navbar />
        <main className="flex-grow flex items-center justify-center py-16 bg-gray-50">
          <div className="bg-white rounded-xl shadow-md p-8 max-w-md w-full mx-4">
            <div className="text-center">
              <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <i className="fa-solid fa-user text-blue-600 text-2xl"></i>
              </div>
              <h2 className="text-2xl font-bold text-gray-900 mb-2">请先登录</h2>
              <p className="text-gray-600 mb-6">登录后即可查看您的个人信息和订单历史</p>
               <button 
                 onClick={() => window.location.href = '/login'}
                 className="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-6 rounded-lg transition-colors shadow-md hover:shadow-lg"
               >
                 <i className="fa-solid fa-sign-in-alt mr-2"></i>
                 立即登录
               </button>
               <button 
                 onClick={() => window.location.href = '/register'}
                 className="w-full mt-4 border border-blue-600 bg-white text-blue-600 hover:bg-blue-50 font-medium py-3 px-6 rounded-lg transition-colors"
               >
                 <i className="fa-solid fa-user-plus mr-2"></i>
                 注册账号
               </button>
            </div>
          </div>
        </main>
        <Footer />
      </div>
    );
  }
  
  return (
    <div className="min-h-screen flex flex-col">
      <Navbar />
      
       <main className="flex-grow bg-gray-50 py-20">
        <div className="container mx-auto px-4">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5 }}
          >
            <h1 className="text-3xl font-bold text-gray-900 mb-8">{t('userProfile')}</h1>
          </motion.div>
          
          <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
            {/* 侧边导航 */}
            <motion.div
              initial={{ opacity: 0, x: -30 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.5, delay: 0.1 }}
            >
              <div className="bg-white rounded-xl shadow-md overflow-hidden sticky top-24">
                <div className="p-6 border-b">
                  <div className="flex items-center">
                    <div className="w-16 h-16 rounded-full overflow-hidden mr-4">
                      <img 
                        src="https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=User%20avatar%20profile%20picture&sign=a47ca4238b884af3e5f2e2dfbbcc7eb9" 
                        alt={profile.fullName}
                        className="w-full h-full object-cover"
                      />
                    </div>
                    <div>
                      <h3 className="font-semibold text-lg text-gray-900">{profile.fullName}</h3>
                      <p className="text-sm text-gray-500">{profile.email}</p>
                    </div>
                  </div>
                </div>
                
                <nav className="p-4">
                  <ul className="space-y-1">
                    <li>
                      <button
                        onClick={() => setActiveTab('profile')}
                        className={cn(
                          "w-full text-left px-4 py-3 rounded-lg transition-colors flex items-center",
                          activeTab === 'profile' 
                            ? "bg-blue-50 text-blue-700 font-medium" 
                            : "text-gray-700 hover:bg-gray-50"
                        )}
                      >
                        <i className="fa-solid fa-user mr-3 w-5 text-center"></i>
                        {t('profile')}
                      </button>
                    </li>
                    <li>
                      <button
                        onClick={() => setActiveTab('orders')}
                        className={cn(
                          "w-full text-left px-4 py-3 rounded-lg transition-colors flex items-center",
                          activeTab === 'orders' 
                            ? "bg-blue-50 text-blue-700 font-medium" 
                            : "text-gray-700 hover:bg-gray-50"
                        )}
                      >
                        <i className="fa-solid fa-boxes mr-3 w-5 text-center"></i>
                        {t('orders')}
                      </button>
                    </li>
                    <li>
                      <button
                        onClick={() => setActiveTab('settings')}
                        className={cn(
                          "w-full text-left px-4 py-3 rounded-lg transition-colors flex items-center",
                          activeTab === 'settings' 
                            ? "bg-blue-50 text-blue-700 font-medium" 
                            : "text-gray-700 hover:bg-gray-50"
                        )}
                      >
                        <i className="fa-solid fa-cog mr-3 w-5 text-center"></i>
                        {t('settings')}
                      </button>
                    </li>
                    <li className="border-t border-gray-100 mt-2 pt-2">
                      <button
                        onClick={logout}
                        className="w-full text-left px-4 py-3 rounded-lg transition-colors flex items-center text-red-600 hover:bg-red-50"
                      >
                        <i className="fa-solid fa-sign-out-alt mr-3 w-5 text-center"></i>
                        {t('logout')}
                      </button>
                    </li>
                  </ul>
                </nav>
              </div>
            </motion.div>
            
            {/* 主内容区域 */}
            <div className="lg:col-span-3 space-y-8">
              {/* 个人资料标签页 */}
              {activeTab === 'profile' && (
                <motion.div
                  initial={{ opacity: 0, x: 30 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ duration: 0.5, delay: 0.2 }}
                  className="bg-white rounded-xl shadow-md overflow-hidden"
                >
                  <div className="p-6 border-b flex justify-between items-center">
                    <h2 className="text-xl font-bold text-gray-900">{t('personalInformation')}</h2>
                    <button
                      onClick={() => setIsEditing(!isEditing)}
                      className="text-blue-600 hover:text-blue-800 font-medium text-sm flex items-center"
                    >
                      {isEditing ? (
                        <>
                          <i className="fa-solid fa-save mr-1"></i>
                          {t('save')}
                        </>
                      ) : (
                        <>
                          <i className="fa-solid fa-edit mr-1"></i>
                          {t('edit')}
                        </>
                      )}
                    </button>
                  </div>
                  
                  <div className="p-6">
                    <form onSubmit={handleProfileSubmit} className="space-y-6">
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                          <label htmlFor="fullName" className="block text-sm font-medium text-gray-700 mb-1">
                            {t('fullName')} <span className="text-red-500">*</span>
                          </label>
                          <input
                            type="text"
                            id="fullName"
                            name="fullName"
                            value={profile.fullName}
                            onChange={(e) => setProfile(prev => ({ ...prev, fullName: e.target.value }))}
                            disabled={!isEditing}
                            className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 transition-colors disabled:bg-gray-50"
                            required
                          />
                        </div>
                        <div>
                          <label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
                            {t('email')} <span className="text-red-500">*</span>
                          </label>
                          <input
                            type="email"
                            id="email"
                            name="email"
                            value={profile.email}
                            onChange={(e) => setProfile(prev => ({ ...prev, email: e.target.value }))}
                            disabled={!isEditing}
                            className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 transition-colors disabled:bg-gray-50"
                            required
                          />
                        </div>
                      </div>
                      
                      <div>
                        <label htmlFor="phone" className="block text-sm font-medium text-gray-700 mb-1">
                          {t('phone')}
                        </label>
                        <input
                          type="tel"
                          id="phone"
                          name="phone"
                          value={profile.phone}
                          onChange={(e) => setProfile(prev => ({ ...prev, phone: e.target.value }))}
                          disabled={!isEditing}
                          className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 transition-colors disabled:bg-gray-50"
                        />
                      </div>
                      
                      <div>
                        <label htmlFor="address" className="block text-sm font-medium text-gray-700 mb-1">
                          {t('address')}
                        </label>
                        <input
                          type="text"
                          id="address"
                          name="address"
                          value={profile.address}
                          onChange={(e) => setProfile(prev => ({ ...prev, address: e.target.value }))}
                          disabled={!isEditing}
                          className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 transition-colors disabled:bg-gray-50"
                        />
                      </div>
                      
                      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <div>
                          <label htmlFor="city" className="block text-sm font-medium text-gray-700 mb-1">
                            {t('city')}
                          </label>
                          <input
                            type="text"
                            id="city"
                            name="city"
                            value={profile.city}
                            onChange={(e) => setProfile(prev => ({ ...prev, city: e.target.value }))}
                            disabled={!isEditing}
                            className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 transition-colors disabled:bg-gray-50"
                          />
                        </div>
                        <div>
                          <label htmlFor="zipCode" className="block text-sm font-medium text-gray-700 mb-1">
                            {t('zipCode')}
                          </label>
                          <input
                            type="text"
                            id="zipCode"
                            name="zipCode"
                            value={profile.zipCode}
                            onChange={(e) => setProfile(prev => ({ ...prev, zipCode: e.target.value }))}
                            disabled={!isEditing}
                            className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 transition-colors disabled:bg-gray-50"
                          />
                        </div>
                        <div>
                          <label htmlFor="country" className="block text-sm font-medium text-gray-700 mb-1">
                            {t('country')}
                          </label>
                          <input
                            type="text"
                            id="country"
                            name="country"
                            value={profile.country}
                            onChange={(e) => setProfile(prev => ({ ...prev, country: e.target.value }))}
                            disabled={!isEditing}
                            className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 transition-colors disabled:bg-gray-50"
                          />
                        </div>
                      </div>
                      
                      {isEditing && (
                        <div className="flex justify-end space-x-4 pt-4 border-t">
                          <button
                            type="button"
                            onClick={() => setIsEditing(false)}
                            className="px-4 py-2 border border-gray-300 text-gray-700 hover:bg-gray-50 rounded-lg transition-colors"
                          >
                            {t('cancel')}
                          </button>
                          <button
                            type="submit"
                            className="px-4 py-2 bg-blue-600 text-white hover:bg-blue-700 rounded-lg transition-colors"
                          >
                            {t('saveChanges')}
                          </button>
                        </div>
                      )}
                    </form>
                  </div>
                </motion.div>
              )}
              
              {/* 订单历史标签页 */}
              {activeTab === 'orders' && (
                <motion.div
                  initial={{ opacity: 0, x: 30 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ duration: 0.5, delay: 0.2 }}
                  className="bg-white rounded-xl shadow-md overflow-hidden"
                >
                  <div className="p-6 border-b">
                    <h2 className="text-xl font-bold text-gray-900">{t('orderHistory')}</h2>
                    <p className="text-gray-600 mt-1">{t('yourOrderHistory')}</p>
                  </div>
                  
                  <div className="divide-y">
                    {orders.map((order) => (
                      <div key={order.id} className="p-6 hover:bg-gray-50 transition-colors">
                        <div className="flex flex-col sm:flex-row sm:justify-between sm:items-start mb-4">
                          <div>
                            <h3 className="font-semibold text-gray-900">
                              {t('orderNumber')}: #{order.id}
                            </h3>
                            <p className="text-sm text-gray-500">{order.date}</p>
                          </div>
                          <div className="mt-2 sm:mt-0">
                            <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getOrderStatusInfo(order.status).className}`}>
                              {getOrderStatusInfo(order.status).text}
                            </span>
                          </div>
                        </div>
                        
                        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center">
                          <div className="text-sm text-gray-600 mb-3 sm:mb-0">
                            <span className="block">{t('total')}: <span className="font-semibold text-gray-900">${order.total.toFixed(2)}</span></span>
                            <span className="block">{t('items')}: {order.items}</span>
                          </div>
                          
                          <button className="text-blue-600 hover:text-blue-800 font-medium text-sm flex items-center">
                         <Link to={`/order/${order.id}`} className="text-blue-600 hover:text-blue-800 font-medium text-sm flex items-center">
                          {t('viewDetails')}
                          <i className="fa-solid fa-arrow-right ml-1 text-xs"></i>
                        </Link>
                            <i className="fa-solid fa-arrow-right ml-1 text-xs"></i>
                          </button>
                        </div>
                      </div>
                    ))}
                  </div>
                  
                  {orders.length === 0 && (
                    <div className="p-12 text-center">
                      <div className="w-20 h-20 mx-auto mb-4 text-gray-300">
                        <i className="fa-solid fa-box-open text-4xl"></i>
                      </div>
                      <h3 className="text-lg font-medium text-gray-900 mb-1">{t('noOrdersFound')}</h3>
                      <p className="text-gray-500 mb-6">{t('noOrdersDescription')}</p>
                      <a 
                        href="/shop" 
                        className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700"
                      >
                        {t('continueShopping')}
                      </a>
                    </div>
                  )}
                </motion.div>
              )}
              
              {/* 设置标签页 */}
              {activeTab === 'settings' && (
                <motion.div
                  initial={{ opacity: 0, x: 30 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ duration: 0.5, delay: 0.2 }}
                  className="space-y-8"
                >
                  {/* 密码修改 */}
                  <div className="bg-white rounded-xl shadow-md overflow-hidden">
                    <div className="p-6 border-b">
                      <h2 className="text-xl font-bold text-gray-900">{t('passwordSettings')}</h2>
                    </div>
                    
                    <div className="p-6">
                      <form className="space-y-6">
                        <div>
                          <label htmlFor="currentPassword" className="block text-sm font-medium text-gray-700 mb-1">
                            {t('currentPassword')}
                          </label>
                          <input
                            type="password"
                            id="currentPassword"
                            className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 transition-colors"
                          />
                        </div>
                        
                        <div>
                          <label htmlFor="newPassword" className="block text-sm font-medium text-gray-700 mb-1">
                            {t('newPassword')}
                          </label>
                          <input
                            type="password"
                            id="newPassword"
                            className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 transition-colors"
                          />
                        </div>
                        
                        <div>
                          <label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700 mb-1">
                            {t('confirmPassword')}
                          </label>
                          <input
                            type="password"
                            id="confirmPassword"
                            className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 transition-colors"
                          />
                        </div>
                        
                        <div className="flex justify-end">
                          <button
                            type="submit"
                            className="px-4 py-2 bg-blue-600 text-white hover:bg-blue-700 rounded-lg transition-colors"
                          >
                            {t('updatePassword')}
                          </button>
                        </div>
                      </form>
                    </div>
                  </div>
                  
                  {/* 通知设置 */}
                  <div className="bg-white rounded-xl shadow-md overflow-hidden">
                    <div className="p-6 border-b">
                      <h2 className="text-xl font-bold text-gray-900">{t('notificationSettings')}</h2>
                    </div>
                    
                    <div className="divide-y">
                      <div className="p-6">
                        <div className="flex items-center justify-between">
                          <div>
                            <h3 className="font-medium text-gray-900">{t('emailNotifications')}</h3>
                            <p className="text-sm text-gray-500">{t('receiveEmailUpdates')}</p>
                          </div>
                          <div className="relative inline-block w-10 align-middle select-none">
                            <input 
                              type="checkbox" 
                              name="emailNotifications" 
                              id="emailNotifications" 
                              className="toggle-checkbox absolute block w-6 h-6 rounded-full bg-white border-4 border-gray-300 appearance-none cursor-pointer checked:right-0 checked:border-blue-600" 
                              defaultChecked
                            />
                            <label htmlFor="emailNotifications" className="toggle-label block overflow-hidden h-6 rounded-full bg-gray-300 cursor-pointer checked:bg-blue-600"></label>
                          </div>
                        </div>
                      </div>
                      
                      <div className="p-6">
                        <div className="flex items-center justify-between">
                          <div>
                            <h3 className="font-medium text-gray-900">{t('smsNotifications')}</h3>
                            <p className="text-sm text-gray-500">{t('receiveSmsUpdates')}</p>
                          </div>
                          <div className="relative inline-block w-10 align-middle select-none">
                            <input 
                              type="checkbox" 
                              name="smsNotifications" 
                              id="smsNotifications" 
                              className="toggle-checkbox absolute block w-6 h-6 rounded-full bg-white border-4 border-gray-300 appearance-none cursor-pointer checked:right-0 checked:border-blue-600" 
                            />
                            <label htmlFor="smsNotifications" className="toggle-label block overflow-hidden h-6 rounded-full bg-gray-300 cursor-pointer checked:bg-blue-600"></label>
                          </div>
                        </div>
                      </div>
                      
                      <div className="p-6">
                        <div className="flex items-center justify-between">
                          <div>
                            <h3 className="font-medium text-gray-900">{t('promotionalOffers')}</h3>
                            <p className="text-sm text-gray-500">{t('receiveSpecialOffers')}</p>
                          </div>
                          <div className="relative inline-block w-10 align-middle select-none">
                            <input 
                              type="checkbox" 
                              name="promotionalOffers" 
                              id="promotionalOffers" 
                              className="toggle-checkbox absolute block w-6 h-6 rounded-full bg-white border-4 border-gray-300 appearance-none cursor-pointer checked:right-0 checked:border-blue-600" 
                              defaultChecked
                            />
                            <label htmlFor="promotionalOffers" className="toggle-label block overflow-hidden h-6 rounded-full bg-gray-300 cursor-pointer checked:bg-blue-600"></label>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </motion.div>
              )}
            </div>
          </div>
        </div>
      </main>
      
      <Footer />
    </div>
  );
}